# Copyright (c) 2025, yuxinyong and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.model.naming import make_autoname


class ShoeLast(Document):
    def autoname(self):
        # 1. 纯手工输入（含last_type后缀）
        if self.last:
            self.last = self.last.upper()
            self.name = self.last
        # 2. 无master last, 自动编号, 加上last type后缀
        elif not self.master_last:
            self.last = make_autoname(self.series_name)
            self.last = self.last.upper()
            self.name = f"{self.last}{self.last_type}"
        elif self.master_last:
            suffix = self.master_last[-1]
            master_last_type = suffix if suffix != "X" else self.master_last[-2]
            # 3. 有master last 且master last的type 不等于当前last type, 替换last type后缀
            if master_last_type != self.last_type:
                self.last = frappe.db.get_value(self.doctype, self.master_last, "last")
                self.name = f"{self.last}{self.last_type}"
            else:
                # 3. 有master last 且master last的type 等于当前last type, 添加X后缀
                self.name = f"{self.master_last}X"
